/* eslint-disable @next/next/no-img-element */
"use client";
import { useState, useEffect } from 'react';
import { signOut } from 'next-auth/react';
import { User, Phone, Mail, Shield, Edit2, CheckCircle, XCircle, LogOut, Bell, Calendar, UserCheck } from 'lucide-react';
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import AppointmentList from './AppointmentList';
import CoursePackageItem from './cursePackageItem';
import { toast } from "sonner";
import { useSearchParams, useRouter, usePathname } from "next/navigation";

const ProfileClient = ({ dict, user, updatePhone, updateName, coaches, clients, campuses, courts, clientCoursePackages }) => {
  const [phone, setPhone] = useState('');
  const [name, setName] = useState(user.name || '');
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [shake, setShake] = useState(false);
  const [isEditingName, setIsEditingName] = useState(false);
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const langFromPath = pathname.split("/")[1] || ""; // 获取 lang

  // 每30秒抖动一次提醒
  useEffect(() => {
    if (!user.phone) {
      const interval = setInterval(() => {
        setShake(true);
        setTimeout(() => setShake(false), 1000);
      }, 30000);
      return () => clearInterval(interval);
    }
  }, [user.phone]);

  // 补全手机号后，若来自定场页则提示返回
  useEffect(() => {
    if (user.phone_number && searchParams.get("redirect") === "court-booking") {
      toast.dismiss();
      toast("手机号已补充完成", {
        description: "点击按钮可返回定场页，10 秒后自动消失",
        action: {
          label: "返回定场",
          onClick: () => {
            router.push(`/${langFromPath}/court-booking`);
          },
        },
        duration: 10000,
      });
    }
  }, [user.phone_number, searchParams, router, langFromPath]);

  const validatePhone = (phone) => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };

  const handleSubmitPhone = async (e) => {
    e.preventDefault();

    if (!validatePhone(phone)) {
      setError(dict.profile.invalidPhone);
      setShake(true);
      setTimeout(() => setShake(false), 1000);
      return;
    }

    try {
      setIsSubmitting(true);
      const result = await updatePhone(phone);
      if (result.success) {
        window.location.reload();
      }
    } catch (error) {
      setError(dict.profile.updateFailed);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSubmitName = async () => {
    if (!name.trim()) {
      setError('名字不能为空');
      return;
    }

    try {
      setIsSubmitting(true);
      const result = await updateName(name);
      if (result.success) {
        setIsEditingName(false);
        window.location.reload();
      }
    } catch (error) {
      setError('更新名字失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleLogout = async () => {
    await signOut({
      redirect: true,
      callbackUrl: '/ty/login'
    });
  };

  const getRoleBadge = (role) => {
    const roleMap = {
      'admin': { label: '管理员', color: 'bg-red-100 text-red-800' },
      'coach': { label: '教练', color: 'bg-blue-100 text-blue-800' },
      'client': { label: '学员', color: 'bg-green-100 text-green-800' }
    };
    return roleMap[role] || { label: role, color: 'bg-gray-100 text-gray-800' };
  };

  return (
    <div className="max-w-4xl mx-auto w-full p-3 sm:p-4 space-y-4 sm:space-y-6">
      {/* 用户信息卡片 */}
      <Card>
        <CardHeader className="pb-2 px-4 sm:px-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3 sm:gap-4">
              <div className="w-12 h-12 sm:w-16 sm:h-16 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                <img src={user?.picture} alt="头像" className="rounded-full w-full h-full object-cover" />
              </div>
              <div className="min-w-0 flex-1">
                {isEditingName ? (
                  <div className="flex items-center gap-2 flex-wrap">
                    <Input
                      type="text"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      className="w-32 sm:w-40"
                      placeholder="输入名字"
                    />
                    <div className="flex gap-1">
                      <Button
                        size="sm"
                        onClick={handleSubmitName}
                        disabled={isSubmitting}
                      >
                        <CheckCircle className="w-4 h-4" />
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => setIsEditingName(false)}
                      >
                        <XCircle className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                ) : (
                  <div className="flex items-center gap-2 flex-wrap">
                    <h2 className="text-lg sm:text-2xl font-bold truncate">{user.name || '未设置名字'}</h2>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => setIsEditingName(true)}
                      className="flex-shrink-0"
                    >
                      <Edit2 className="w-4 h-4" />
                    </Button>
                  </div>
                )}
                <div className="flex items-center gap-2 mt-1">
                  {user.role && (
                    <Badge variant={user.role === 'admin' ? 'destructive' : 'secondary'} className="text-xs">
                      {user.role === 'admin' ? '管理员' : getRoleBadge(user.role).label}
                    </Badge>
                  )}
                </div>
              </div>
            </div>
          </div>
        </CardHeader>

        <CardContent className="px-4 sm:px-6">
          <Separator className="my-4" />

          {/* 联系信息 */}
          <div className="space-y-4">
            {user.phone_number ? (
              <div className="flex items-center gap-2 text-muted-foreground">
                <Phone className="w-4 h-4 flex-shrink-0" />
                <span className="text-sm sm:text-base">{user.phone_number}</span>
              </div>
            ) : (
              <div className={`bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-200 rounded-xl p-4 sm:p-6 ${shake ? 'animate-shake' : ''}`}>
                {/* 友好的引导文案 */}
                <div className="mb-4 space-y-3">
                  <div className="flex items-center gap-2 text-blue-800">
                    <UserCheck className="w-5 h-5 flex-shrink-0" />
                    <h3 className="font-semibold text-sm sm:text-base">完善手机号，享受更好服务</h3>
                  </div>
                  <div className="space-y-2 text-xs sm:text-sm text-blue-700">
                    <div className="flex items-start gap-2">
                      <Calendar className="w-4 h-4 mt-0.5 flex-shrink-0" />
                      <span>及时接收预约确认、课程变更等重要通知</span>
                    </div>
                    <div className="flex items-start gap-2">
                      <Shield className="w-4 h-4 mt-0.5 flex-shrink-0" />
                      <span>保障您的场地预约权益，避免因联系不上造成的损失</span>
                    </div>
                    <div className="flex items-start gap-2">
                      <Bell className="w-4 h-4 mt-0.5 flex-shrink-0" />
                      <span>紧急情况时能够第一时间联系到您</span>
                    </div>
                  </div>
                  <div className="text-xs text-blue-600 bg-blue-100 rounded-lg p-2">
                    <span>💡 我们承诺严格保护您的隐私信息，绝不用于其他用途</span>
                  </div>
                  <div className="text-xs text-orange-700 bg-orange-100 border border-orange-200 rounded-lg p-3">
                    <div className="flex items-start gap-2">
                      <span className="text-orange-600">⚠️</span>
                      <div>
                        <div className="font-medium mb-1">请务必填写正确手机号</div>
                        <div>手机号一经提交不可更改，如需变更请到场地联系教务老师处理</div>
                      </div>
                    </div>
                  </div>
                </div>

                <form onSubmit={handleSubmitPhone} className="space-y-4">
                  <div>
                    <Label className="text-blue-800 text-sm font-medium">
                      请输入手机号码
                    </Label>
                    <Input
                      type="tel"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      className="mt-2 text-base border-blue-300 focus:border-blue-500 focus:ring-blue-500"
                      placeholder="请输入11位手机号码"
                      disabled={isSubmitting}
                    />
                    {error && <p className="text-red-500 text-xs sm:text-sm mt-2">{error}</p>}
                  </div>
                  <Button
                    type="submit"
                    className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2.5 text-sm sm:text-base"
                    disabled={isSubmitting}
                  >
                    {isSubmitting ? '提交中...' : '确认提交'}
                  </Button>
                </form>
              </div>
            )}
          </div>

          <Separator className="my-4" />

          {/* 退出登录按钮 */}
          <Button
            variant="destructive"
            onClick={handleLogout}
            className="w-full py-2.5 text-sm sm:text-base"
          >
            <LogOut className="w-4 h-4 mr-2" />
            退出登录
          </Button>
        </CardContent>
      </Card>

      {/* 课程套餐 */}
      {user.role === 'client' && (
        <Card>
          <CardHeader className="px-4 sm:px-6">
            <CardTitle className="text-lg sm:text-xl">课程套餐</CardTitle>
          </CardHeader>
          <CardContent className="px-4 sm:px-6">
            <div className="flex flex-col gap-3">
              {clientCoursePackages.map((coursePackage) => (
                <CoursePackageItem key={coursePackage.id} coursePackage={coursePackage} coaches={coaches} />
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 预约列表 */}
      {user.role !== 'admin' && (
        <Card>
          <CardContent className="pt-4 sm:pt-6 px-4 sm:px-6">
            <AppointmentList user={user} coaches={coaches} clients={clients} campuses={campuses} courts={courts} />
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default ProfileClient;